package com.itheima.service.impl;

import cn.itheima.health.entity.QueryPageBean;
import cn.itheima.health.service.CheckGroupService;
import cn.itheima.health.service.CheckItemService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupMapper checkGroupMapper;

    @Autowired
    private  CheckItemMapper checkItemMapper;


    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitems) {
        //   检查组 添加一条记录  返回主键    中间表需要
        checkGroupMapper.add(checkGroup);  //  Mybatis 主键 注入  实体类属性id

        Integer checkGroupId = checkGroup.getId();  //  新增记录主键

        if(checkitems!=null){
            //  循环更新中间表
            for (Integer checkitemid : checkitems) {
                checkGroupMapper.addCheckGroupAndCheckItems(checkGroupId,checkitemid);
            }

        }



    }

    @Override
    public Map findPage(QueryPageBean queryPageBean) {
        Map map  = new HashMap();
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        List<CheckGroup> list  = checkGroupMapper.findPage(queryPageBean.getQueryString());
        PageInfo<CheckGroup> pageInfo = new PageInfo<CheckGroup>(list);
        map.put("list",pageInfo.getList());
        map.put("total",pageInfo.getTotal());
        return map;
    }

    @Override
    public Map findCheckitemsByGroupId(Integer id) {
        Map map = new HashMap();
        List<CheckItem> list = checkItemMapper.findAll();
        Integer [] checkitems  = checkGroupMapper.findCheckitemsByGroupId(id);
        map.put("list",list);
        map.put("checkitems",checkitems);
        return map;
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitems) {

        //  检查组信息修改  update  t_checkgroup  set  xxx where  id = #{id}

        checkGroupMapper.edit(checkGroup);


        Integer checkGroupId = checkGroup.getId();  // 检查组的id
        //  1 先接触关系  删除中间表数据   根据 检查组id
        checkGroupMapper.removeCheckItemsByGroupId(checkGroupId);

        if(checkitems!=null){
            //  循环更新中间表
            for (Integer checkitemid : checkitems) {
                checkGroupMapper.addCheckGroupAndCheckItems(checkGroupId,checkitemid);
            }

        }

    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupMapper.findAll();
    }
}











